package ibmetp.mis.controller.dept;

import ibmetp.mis.common.Constants;
import ibmetp.mis.dao.UserDao;
import ibmetp.mis.json.DateJsonValueProcessor;
import ibmetp.mis.service.PageService;
import ibmetp.mis.serviceImpl.DeptServiceImpl;
import ibmetp.mis.vo.Dept;
import ibmetp.mis.vo.Page;
import ibmetp.mis.vo.ResNode;
import ibmetp.mis.vo.Resource;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

/**
 * Servlet implementation class DeptTreeServlet
 */
public class DeptTreeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeptTreeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	     request.setCharacterEncoding(Constants.ENCODING_UTF8);
	     System.out.println("call DeptTreeServlet...");
	     String id=request.getParameter("id")!=null?request.getParameter("id"):"0";
		 System.out.println(id);
       		Dept dept=new Dept();
			
			//dept.setDeptId(Long.getLong(request.getParameter("deptId")));
			dept.setDeptNo(request.getParameter("deptNo"));
			dept.setDeptName(request.getParameter("deptName"));
			//dept.setManager(ud.getUserById(Long.getLong(request.getParameter("manager"))));

			//System.out.println("SearchConditions:"+dept);
			
			//查询数据
			PageService us=new DeptServiceImpl();
			Page p=us.getPage(1, 1000, dept);	   
			
			//输出JSON数据
			JSONArray o=new JSONArray();
			 JsonConfig jsonConfig = new JsonConfig();  
		     jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));  
	
			//得到pid的子节点
			List<Dept> list=p.getList();
			for(int i=0;i<list.size();i++)
			{      
				    Dept d=list.get(i);			    
					ResNode rn=new ResNode();
					rn.setId(d.getDeptId());
					rn.setText(d.getDeptName());
					rn.setState("open");
					rn.setAttributes(new JSONObject().fromObject(d, jsonConfig));
					o.add(rn);
				
			}	
			
			
			response.setCharacterEncoding(Constants.ENCODING_UTF8);
			response.getWriter().write(o.toString());
	}

}
